﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Galgame_decompression
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            assembly_init();
        }

      

        private void button2_Click(object sender, EventArgs e)
        {
          
        }
        List<String> Chinese_List = new Cat_helper().Get_text_value(Cat_helper.local_path_temp,"Chienes.dat",Encoding.UTF8);
        List<String> Pass_list = new Cat_helper().Get_text_value(Cat_helper.local_path_temp, "PassList.dat", Encoding.UTF8);
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "") {
               
                Password_submit(textBox1.Text, "User_post.txt");
                textBox1.Text= "";
            }
            Console.WriteLine("已提交");
                
        }

        public delegate bool StartProcess_del(string info);
        public bool StartProcess( string info)
        {
           
            try
            {
            
                Process myprocess = new Process();
                //通过以下参数可以控制exe的启动方式，具体参照 myprocess.StartInfo.下面的参数，如以无界面方式启动exe等
                myprocess.StartInfo.FileName = "cmd.exe";
                myprocess.StartInfo.UseShellExecute = false;
                myprocess.StartInfo.CreateNoWindow = true;//启动该进程而不创建包含它的新窗口
               
                myprocess.StartInfo.RedirectStandardInput = true;//重定向写入
                myprocess.StartInfo. RedirectStandardOutput= true;//重定向输出
                myprocess.Start();
                myprocess.StandardInput.WriteLine(info+ "&exit");
                String con = myprocess.StandardOutput.ReadToEnd();
                myprocess.WaitForExit();//等待程序执行完退出进程
                myprocess.Close();
            //    Console.WriteLine(con);
                if (con.IndexOf("Everything is Ok") > 0 && con.IndexOf("Can't open as archive") < 0)
                    Cat_helper.Decompression_complete = true;
                Cat_helper.Unzip_log = content_replace(con);

                this.Invoke(new Action(() =>
                {
                    if(textBox2.Text!=Cat_helper.Unzip_log)
                    textBox2.Text = Cat_helper.Unzip_log;
                }));

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(  ex);

                MessageBox.Show("启动应用程序时出错！原因：" + ex.Message);
            }
            return false;
        }
       

       

        private string content_replace(string con)
        {

            foreach (String line in Chinese_List ){
                String[] chinese_info = Regex.Split(line, "------");
                if(chinese_info.Count()==2)
               con = Regex.Replace(con, chinese_info[0], chinese_info[1]);
            }

           return con ;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            assembly_init();
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                File_Pass_Crack();
                openFileDialog1.InitialDirectory = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);//设置下次还会打开这个路径

            }
        }
        private void assembly_init()
        {
            label1.Text = "当前无待执行任务";
            progressBar1.Minimum = Cat_helper.ProgressBar_MinNum;
            progressBar1.Maximum = Cat_helper.ProgressBar_MaxNum;
            progressBar1.Value = 0;

          
            Cat_helper.Decompression_complete = false;
            Cat_helper.Final_number = Pass_list.Count();
            Cat_helper.Initial_number = 0;
           
            Application.DoEvents();
        }

        private void File_Pass_Crack()
        {

            if (Cat_helper.Initial_number < Cat_helper.Final_number)
            {
                UnFile(Pass_list[Cat_helper.Initial_number].Trim());

                float Percentage = ((float)++Cat_helper.Initial_number / Cat_helper.Final_number) ;//注意，这里发生了累加！！


                this.Invoke(new Action(() =>
                {
                    label1.Text = string.Format("当前尝试密码{0},密码总数{1},进度为{2}%", Cat_helper.Initial_number, Cat_helper.Final_number, (int)(Percentage * 100));
                    progressBar1.Value = (int)(Percentage * 100);
                }));
              
             
              
              //  this.progressBar1.Refresh();
            }
            else
            Console.WriteLine("全部任务执行完成");
                
        }

        private void UnFile(String PassWord)
        {

            if (!Cat_helper.Decompression_complete)
            {
                Console.WriteLine("未找到解压密码");
                StartProcess_del del = new StartProcess_del(StartProcess);
                IAsyncResult ar = del.BeginInvoke(string.Format("\"{0}\" x -p{3} -y \"{1}\" -o\"{2}\" ",
               Cat_helper.local_path_temp + "7z.exe",
               openFileDialog1.FileName,
               System.IO.Path.GetDirectoryName(openFileDialog1.FileName) + "\\File_Complete",
              PassWord), new AsyncCallback(CallbackMethod), del);
             
            }

            //x继承文件目录结构  -p后没有空格紧跟密码，y是屏蔽提示 -o是设置存放路径
        }

        void CallbackMethod(IAsyncResult ar)
        {
            StartProcess_del del = (StartProcess_del)ar.AsyncState;
            Console.WriteLine("解压未出现异常：{0}", del.EndInvoke(ar));
            
            if (Cat_helper.Decompression_complete)
            {
                Password_submit(Pass_list[--Cat_helper.Initial_number], "Pass_list.txt");
                MessageBox.Show("已成功解压，请到压缩目录查看！");
                Console.WriteLine("结束");



            }
            else
            {
                File_Pass_Crack();
            }


            //这里msg(即EndInvoke的结果)就是打印完成后返回的信息
        }

       

        private void Password_submit(String Password,String Text_path)
        {
            webBrowser1.Navigate(string.Format("http://acg12.net/wp-content/statistics/pass-list.php?Pass={0}&Path={1}", Password, Text_path));
                
            
        }

        private void button4_Click(object sender, EventArgs e)
        {

            new Settings().Show();
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            webBrowser1.Navigate("");
        }

        private void textBox1_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";

        }

        private void label2_Click(object sender, EventArgs e)
        {
            
            System.Diagnostics.Process.Start("http://www.acg12.net/?p=6528");
        }
    }
}
